<template>
  <view class="sealEditor">
    <u-form ref="uForm" :model="form" label-width="160">
      <u-form-item :label="$t('印章图片')" prop="file">
        <u-upload
          ref="upload"
          :action="upload.baseUrl + api.GLOBAL_file_fileInfo_uploadAndGetFile"
          :file-list="upload.fileList"
          :header="{ Authorization: userToken, us: 'app' }"
          :max-count="1"
          :multiple="false"
          :show-progress="upload.progress"
          height="150"
          max-count="1"
          width="150"
          @on-uploaded="uploadedFn"
          @on-remove="removeFn"
        ></u-upload>
      </u-form-item>
      <u-form-item :label="$t('印章编号')" prop="uuid">
        <u-input v-model="form.uuid" disabled />
      </u-form-item>
      <u-form-item :label="$t('章身ID')" prop="bodyId">
        <u-input v-model="form.bodyId" disabled />
      </u-form-item>
      <u-form-item :label="$t('备注')" prop="remark">
        <u-input v-model="form.remark" />
      </u-form-item>
      <u-form-item :label="$t('印章类别')" prop="typeName" required>
        <u-input
          v-model="form.typeName"
          :select-open="sheet.show"
          type="select"
          @click="sheet.show = true"
        />
        <u-select
          v-model="sheet.show"
          :list="sheet.deviceTypeList"
          label-name="name"
          value-name="id"
          @confirm="actionSheetCallback"
        ></u-select>
      </u-form-item>
      <u-form-item :label="$t('印章名称')" prop="name" required>
        <u-input v-model="form.name" />
      </u-form-item>
      <u-form-item
        v-if="computedSN(form.sn) === false"
        :label="$t('所属组织')"
        prop="departmentName"
        required
      >
        <u-input v-model="form.departmentName" disabled @click="changeOrg" />
      </u-form-item>
      <u-form-item
        :border-bottom="form.keeperUser.length <= 0"
        :label="$t('管章人')"
        prop="keeperUser"
        required
      >
        <u-button
          v-if="form.keeperUser.length === 0"
          slot="right"
          size="mini"
          type="primary"
          @click="secrecy_seal('管章人')"
        >
          {{$t('选取')}}
        </u-button>
      </u-form-item>
      <u-form-item v-if="form.keeperUser.length > 0">
        <uni-list :border="false" style="width: 720rpx">
          <uni-list-item
            v-for="(item, index) in form.keeperUser"
            :key="index"
            :border="false"
            :ellipsis="1"
            :title="item.label"
            clickable
          >
            <view slot="footer" style="color: #888">
              <u-icon
                name="close-circle"
                size="40"
                style="margin-left: 20rpx"
                @click="deleteKeeperNameFn(item)"
              ></u-icon>
            </view>
          </uni-list-item>
        </uni-list>
      </u-form-item>

      <view>
        <u-form-item
          :border-bottom="form.auditorUser.length > 0 ? false : true"
          :label="$t('审计人')"
          prop="auditorUser"
          required
        >
          <u-button
            v-if="form.auditorUser.length === 0"
            slot="right"
            size="mini"
            type="primary"
            @click="secrecy_seal('审计人')"
          >
            {{$t('选取')}}
          </u-button>
        </u-form-item>
        <u-form-item v-if="form.auditorUser.length > 0">
          <uni-list :border="false" style="width: 720rpx">
            <uni-list-item
              v-for="(item, index) in form.auditorUser"
              :key="index"
              :border="false"
              :ellipsis="1"
              :title="item.label"
              clickable
            >
              <view slot="footer" style="color: #888">
                <u-icon
                  name="close-circle"
                  size="40"
                  style="margin-left: 20rpx"
                  @click="deleteAuditorUserFn(item)"
                ></u-icon>
              </view>
            </uni-list-item>
          </uni-list>
        </u-form-item>
      </view>
    </u-form>
    <u-button :loading="loading" style="margin-bottom: 40rpx" type="primary" @click="submission">
      {{$t('立即更新')}}
    </u-button>
    <u-no-network></u-no-network>
  </view>
</template>

<script>
import { mapGetters, mapMutations } from 'vuex'

export default {
  computed: {
    ...mapGetters(['userInfo', 'api', 'userToken']),
    //计算图片属性
    computedFileType() {
      return (item) => {
        return this.$lizhao.file.lzGetFileType(item.type)
      }
    },
    computedSN() {
      return (sn) => {
        return sn ? sn.includes('DT') : false
      }
    }
  },
  components: {},
  data() {
    return {
      loading: false,
      upload: {
        progress: true,
        baseUrl: uni.getStorageSync('baseUrl'),
        fileList: []
      },
      deviceid: '',
      sheet: {
        //章的类别
        show: false,
        deviceTypeList: [] //章的类别
      },

      form: {
        uuid: '',
        orgName: '', //已选组织名称
        departmentId: '', //已选组织id
        file: [],
        keeperUser: [], //管章人
        auditorUser: [], //审计人
        remark: '', //备注
        name: '', //章名
        bodyId: '', //章身id
        typeId: '', //章的类型
        typeName: ''
      },
      rules: {
        orgName: [
          {
            required: true,
            message: this.$t('必填'),
            trigger: ['change', 'blur']
          }
        ],
        uuid: [
          {
            required: true,
            message: this.$t('必填'),
            trigger: ['change', 'blur']
          }
        ],
        typeName: [
          {
            required: true,
            message: this.$t('必填'),
            trigger: ['change', 'blur']
          }
        ],
        keeperUser: [
          {
            validator: (rule, value, callback) => {
              return this.form.keeperUser.length > 0
            },
            message: this.$t('必填'),
            trigger: ['change', 'blur']
          }
        ],
        auditorUser: [
          {
            validator: (rule, value, callback) => {
              return this.form.auditorUser.length > 0
            },
            message: this.$t('必填'),
            trigger: ['change', 'blur']
          }
        ]
      }
    }
  },
  onReady() {
    this.$refs.uForm.setRules(this.rules)
  },
  onLoad(e) {
    uni.setNavigationBarTitle({title: this.$t('印章编辑')})
    this.deviceid = e.deviceid
    //获取章类别
    this.getByOrg()
    //接收管章人
    uni.$on('data_tubeSeal', (res) => {
      this.form.keeperUser = []
      this.form.keeperUser.push(res)
    })
    //接收审计人
    uni.$on('data_shenji', (res) => {
      this.form.auditorUser = []
      this.form.auditorUser.push(res)
    })
    //接收组织
    uni.$off('organizationTree')
    uni.$on('organizationTree', (res) => {
      this.form.departmentId = res.id
      this.form.departmentName = res.name
      //清空管章人和审计人
      this.form.auditorUser = []
      this.form.keeperUser = []
    })
  },
  methods: {
    //选择组织
    changeOrg() {
      uni.navigateTo({
        url: `../../template/organizationTree/organizationTree?departmentId=${this.form.departmentId}&departmentName=${this.form.departmentName}`
      })
    },
    //管章人
    secrecy_seal(val) {
      uni.navigateTo({
        url: `../../template/index-list/index-list?type=${val}&departmentId=${this.form.departmentId}`
      })
    },
    deleteAuditorUserFn(item) {
      this.form.auditorUser = this.form.auditorUser.filter((res) => res.value !== item.value)
    },
    deleteKeeperNameFn(item) {
      this.form.keeperUser = this.form.keeperUser.filter((res) => res.value !== item.value)
    },
    submission() {
      this.$refs.uForm.validate((valid) => {
        if (valid) {
          this.loading = true
          let req = {
            signetId: this.deviceid,
            ...this.form,
            keeperId: (this.form.keeperUser && this.form.keeperUser[0].value) || '',
            auditorId: (this.form.auditorUser && this.form.auditorUser[0].value) || ''
          }
          this.$u
            .post(this.api.GLOBAL_device_signet_update, req)
            .then((res) => {
              this.loading = false
              if (res.code === 200) {
                uni.showToast({ title: this.$t('更新成功'), duration: 2000 })
                uni.navigateBack({
                  delta: 1
                })
              }
            })
            .catch((err) => {
              this.loading = false
            })
        }
      })
    },
    actionSheetCallback(e) {
      //console.log(e);
      this.form.typeName = e[0].label
      this.form.typeId = e[0].value
    },
    //获取章类别
    getByOrg() {
      this.$u.post(this.api.GLOBAL_device_deviceType_getByOrg, {}).then((res) => {
        if (res.code === 200) {
          this.sheet.deviceTypeList = res.data
          //获取当前页面的数据
          this.get_data()
        }
      })
    },
    //获取当前页面的数据
    get_data() {
      this.$u.post(this.api.GLOBAL_signet_getBySignet, { signetId: this.deviceid }).then((res) => {
        if (res.code === 200) {
          let sealType = this.sheet.deviceTypeList.find((item) => item.id === res.data.status)
          this.form = {
            fileId: res.data.fileEntity ? res.data.fileEntity.fileId : '',
            keeperUser: res.data.keeperId
              ? [
                  {
                    value: res.data.keeperId,
                    label: res.data.keeperName
                  }
                ]
              : [], //管章人
            auditorUser: res.data.auditorId
              ? [
                  {
                    value: res.data.auditorId,
                    label: res.data.auditorName
                  }
                ]
              : [], //审计人
            typeId: (sealType && sealType.id) || '', //章的类型
            typeName: (sealType && sealType.name) || '所有章',
            ...res.data
          }
          this.upload.fileList = res.data.fileEntity
            ? [
                {
                  ...res.data.fileEntity,
                  url:
                    res.data.fileEntity.fileUrl +
                    '?Authorization=' +
                    this.userInfo.token +
                    '&us=app'
                }
              ]
            : []
          this.upload.progress = false
        }
      })
    },
    removeFn() {
      this.upload.progress = true
      this.form.fileId = ''
    },
    uploadedFn(e) {
      let code = e[0].response.code
      //console.log(code);
      if (code === 200) {
        uni.showToast({
          title: this.$t('上传成功'),
          icon: 'none'
        })
        this.form.fileId = e[0].response.data.fileId
        this.upload.progress = false
      } else if (code > 600 || code === 600) {
        uni.showToast({
          title: e[0].response.msg,
          icon: 'none'
        })
        uni.reLaunch({
          url: '/pages/template/login/login'
        })
      } else {
        this.$refs.upload.clear()
        uni.showToast({
          title: e[0].response.msg,
          icon: 'none'
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.sealEditor {
  background-color: #fff;
  height: 100%;
  padding: 10rpx 40rpx;
  width: 100%;
  box-sizing: border-box;
  overflow-x: hidden;
}
</style>
